/**
 * 
 */
package vn.lumi.smarthome.ui.scene;

/**
 * @author HuyHieu
 *
 */

import java.util.ArrayList;

import com.slidingmenu.lib.app.SlidingFragmentActivity;

import vn.lumi.smarthome.Config;
import vn.lumi.smarthome.LumiHome;
import vn.lumi.smarthome.R;
import vn.lumi.smarthome.io.database.TBL_Scene;
import vn.lumi.smarthome.io.model.Scene;

import vn.lumi.smarthome.service.VibrateThread;
import vn.lumi.smarthome.ui.base.MainActivity;
import vn.lumi.smarthome.ui.base.MainFragment;
import vn.lumi.smarthome.ulti.ChangeFont;
import vn.lumi.smarthome.ulti.LogUltis;
import vn.lumi.smarthome.ulti.Preference;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class EditListSceneFragment extends MainFragment implements
		LoaderCallbacks<Cursor> {
	public static final String EDIT_LIST_SCENE_FRAGMENT = "SceneFragment";

	private ListView mListScenes;
	private SceneEditAdapter mSceneEditAdapter;

	private static EditListSceneFragment editSceneFragment;
	// Khai bao ID cua Loader
	private static final int LOADER_ID = 1;

	public EditListSceneFragment() {
		LogUltis.i(EDIT_LIST_SCENE_FRAGMENT, "create EditSceneFragment");
	}

	public static EditListSceneFragment newInstance(int floor_id, int room_id,
			String nameRoom, String nameFloor) {
		if (editSceneFragment == null) {
			editSceneFragment = new EditListSceneFragment();
		}
		Bundle bundle = new Bundle();
		bundle.putInt(FLOOR_ID, floor_id);
		bundle.putInt(ROOM_ID, room_id);
		bundle.putString(MainFragment.NAME_ROOM, nameRoom);
		bundle.putString(MainFragment.NAME_FLOOR, nameFloor);
		editSceneFragment.setArguments(bundle);
		return editSceneFragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mFloor_id = getArguments().getInt(FLOOR_ID);
		mRoom_id = getArguments().getInt(ROOM_ID);
		nameRoom = getArguments().getString(MainFragment.NAME_ROOM);
		nameFloor = getArguments().getString(MainFragment.NAME_FLOOR);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		Config.configLanguage(getActivity().getBaseContext(),
				Preference.getLanguage(getActivity().getApplicationContext()));// Thiet lap
		// ngon ngu
		// Dung chung voi scene
		View view = inflater.inflate(R.layout.fragment_edit_scene, container,
				false);
		init_view(view);

		return view;
	}

	private void init_view(View view) {
		setupActionBar(view);

		// Dung chung voi scene
		mListScenes = (ListView) view
				.findViewById(R.id.fragment_scene_list_scene);
		mSceneEditAdapter = new SceneEditAdapter(getActivity(), null,
				CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		mSceneEditAdapter.initData(mFloor_id, mRoom_id);

		mListScenes.setAdapter(mSceneEditAdapter);
	}

	@Override
	public void setupActionBar(View view) {
		// TODO Auto-generated method stub
		super.setupActionBar(view);
		setButtonToScence();
		btn_editScene.setBackgroundResource(R.drawable.img_ok);

		// Set bien bao hieu la o trong editfragment
		// isPressableEditScene = false;
	}

	@Override
	public void onResume() {
		super.onResume();

		// load data
		refreshData(mFloor_id, mRoom_id, nameRoom, nameFloor);

		// kiem tra xem co cho phep rung khong
		Config.isVibrate = Preference.getVibrate(getActivity());
		// Config.configLanguage(getActivity().getBaseContext(),
		// Preference.getLanguage(getActivity().getApplicationContext()));// Thiet lap
		// // ngon ngu
	}

	@Override
	public void refreshData(int floor_id, int room_id, String nameRoom,
			String nameFloor) {
		mFloor_id = floor_id;
		mRoom_id = room_id;
		MainFragment.nameRoom = nameRoom;
		MainFragment.nameFloor = nameFloor;
		Bundle bundle = new Bundle();
		bundle.putInt(FLOOR_ID, mFloor_id);
		bundle.putInt(ROOM_ID, mRoom_id);
		getLoaderManager().restartLoader(LOADER_ID, bundle, this);
		mSceneEditAdapter.refreshData(floor_id, room_id);
	}

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {
		int room_id = bundle.getInt(ROOM_ID);
		String selection = TBL_Scene.ROOM_ID + "=?";
		String[] selectionArgs = new String[] { room_id + "" };
		return new CursorLoader(getActivity(), TBL_Scene.CONTENT_URI_SCENE,
				null, selection, selectionArgs, null);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
		mSceneEditAdapter.swapCursor(arg1);
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		mSceneEditAdapter.swapCursor(null);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		FragmentManager fragmentManager = getActivity()
				.getSupportFragmentManager();
		FragmentTransaction transaction = fragmentManager.beginTransaction();
		if (Config.isVibrate)
			new VibrateThread(getActivity().getApplicationContext()).start();
		switch (v.getId()) {
		case R.id.layout_actionbar_home:
			if (MainActivity.isTabletTab()) {
				((SlidingFragmentActivity) getActivity()).getSlidingMenu()
						.showMenu(true);
			}
			break;
		case R.id.layout_actionbar_switch:
			setButtonToDevice();
			isDeviceButton = true;
			setTitleActionbar(nameRoom + "-" + nameFloor);
			MainFragment mainFragment = MainFragment.newInstance(mFloor_id,
					mRoom_id, MainFragment.SCREEN_DEVICE, nameRoom, nameFloor);
			transaction.replace(R.id.activity_main_content, mainFragment,
					"main");
			transaction.setCustomAnimations(
					R.animator.fragment_slide_left_enter,
					R.animator.fragment_slide_left_exit,
					R.animator.fragment_slide_right_enter,
					R.animator.fragment_slide_right_exit);
			transaction.commit();
			btn_editScene
					.setBackgroundResource(R.drawable.img_editscene_selector);

			// isPressableEditScene = true;
			break;
		case R.id.layout_actionbar_turnoff:
			turnAllOffOnRoom(mRoom_id);
			break;
		case R.id.layout_actionbar_turnon:
			turnAllOnOnRoom(mRoom_id);
			break;
		case R.id.layout_actionbar_addScence:
			// Intent intent = new Intent(getActivity(), AddSceneActivity.class);
			// intent.putExtra(AddSceneActivity.EXTRA_FLOOR_ID, mFloor_id);
			// intent.putExtra(AddSceneActivity.EXTRA_ROOM_ID, mRoom_id);
			// startActivityForResult(intent, MainActivity.ADD_SCENE_REQUEST);

				AddSceneFragmet addSceneFragmet = AddSceneFragmet.newInstance(mRoom_id,
						mFloor_id, nameRoom, nameFloor,
						AddSceneFragmet.TYPE_EDIT_LIST_FRAGMENT);
			transaction.replace(R.id.activity_main_content, addSceneFragmet,
					AddSceneFragmet.ADD_SCENE_FRAGMENT);
			transaction.addToBackStack(null);
			transaction.setCustomAnimations(
					R.animator.fragment_slide_left_enter,
					R.animator.fragment_slide_left_exit,
					R.animator.fragment_slide_right_enter,
					R.animator.fragment_slide_right_exit);

			// Commit the transaction
			transaction.commit();
			break;
		case R.id.layout_actionbar_editScence:
			// if (isPressableEditScene) {
			//
			// // EditListSceneFragment editFragment = EditListSceneFragment
			// // .newInstance(mFloor_id, mRoom_id, nameRoom, nameFloor);
			// // transaction.replace(R.id.activity_main_content, editFragment,
			// // "editScene").commit();
			// // isPressableEditScene = false;
			// // btn_editScene.setBackgroundResource(R.drawable.img_ok);
			// } else {
			setTitleActionbar(nameRoom + "-" + nameFloor);
			MainFragment mainFragment1 = MainFragment.newInstance(mFloor_id,
					mRoom_id, MainFragment.SCREEN_SCENE, nameRoom, nameFloor);
			transaction.replace(R.id.activity_main_content, mainFragment1,
					"main").commit();
			btn_editScene
					.setBackgroundResource(R.drawable.img_editscene_selector);

			// isPressableEditScene = true;

			// }
			break;
		default:
			break;
		}
	}

	private class SceneEditAdapter extends CursorAdapter {
		int floor_id = 0;
		int room_id = 0;
		Context context;
		// private static final String TAG = "SceneAdapter";
		public BroadcastReceiver mDelSceneReceiver;

		public SceneEditAdapter(Context context, Cursor c, int flags) {
			super(context, c, flags);
			this.context = context;
		}

		public void initData(int floorID, int roomID) {
			floor_id = floorID;
			room_id = roomID;
		}

		public void refreshData(int floorID, int roomID) {
			floor_id = floorID;
			room_id = roomID;
		}

		@Override
		public void bindView(View view, final Context context, Cursor cursor) {
			final TextView txtName = (TextView) view
					.findViewById(R.id.item_listview_scene_edit_txt_name);
			ImageView imv_delete = (ImageView) view
					.findViewById(R.id.item_listview_scene_edit_delete);

			// set name
			final String sceneName = cursor.getString(cursor
					.getColumnIndex(TBL_Scene.NAME));
			txtName.setText(sceneName);

			// set state image
			final int state = cursor.getInt(cursor
					.getColumnIndex(TBL_Scene.STATE));
			if (state == Scene.SCENE_STATE_OFF) {

				txtName.setBackgroundResource(R.drawable.img_bg_dev_normal_name_off);
			} else if (state == Scene.SCENE_STATE_ON) {

				txtName.setBackgroundResource(R.drawable.img_bg_dev_normal_name_on);
			}

			final int sceneID = cursor.getInt(cursor
					.getColumnIndex(TBL_Scene._ID));

			imv_delete.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					if (Config.isVibrate)
						new VibrateThread(getActivity().getApplicationContext())
								.start();
					ArrayList<Integer> selectedScenes = new ArrayList<Integer>();
					selectedScenes.add(sceneID);

					// del scenes
					ContentValues values = new ContentValues();
					values.put(
							"Scene IDs",
							EditListSceneFragment
									.convertIntArrayToString(convertArrayListToArray(selectedScenes)));
					context.getContentResolver().update(
							TBL_Scene.CONTENT_URI_DELETE_SCENE, values, null,
							null);

					// show dialog
					ProgressDialog dialog = new ProgressDialog(
							new ContextThemeWrapper(context,
									R.style.AlertDialogCustom));
					dialog.setMessage(context
							.getString(R.string.txt_saving_scene_in_HC));
					dialog.setCancelable(false);
					dialog.show();

					// Thay doi font chu cua Dialog
					ChangeFont changeFont = new ChangeFont(context);
					TextView textView = (TextView) dialog
							.findViewById(android.R.id.message);
					textView = changeFont.changeFontTextView(textView,
							R.string.txt_saving_scene_in_HC, LumiHome.font, 16,
							Gravity.NO_GRAVITY, context.getResources()
									.getColor(R.color.greenActionbar));

					// set broadcast receiver
					mDelSceneReceiver = new DelSceneReceiver(dialog);
					IntentFilter filter = new IntentFilter();
					filter.addAction(context
							.getString(R.string.txt_vn_lumi_smarthome_del_scenes_successful));
					filter.addAction(context
							.getString(R.string.txt_vn_lumi_smarthome_del_scenes_failed));
					context.registerReceiver(mDelSceneReceiver, filter);
				}

			});
			// set schedule
			final int mode = cursor.getInt(cursor
					.getColumnIndex(TBL_Scene.MODE));
			final int hour = cursor.getInt(cursor
					.getColumnIndex(TBL_Scene.HOUR));
			final int minute = cursor.getInt(cursor
					.getColumnIndex(TBL_Scene.MINUTE));

			// config onclick --> edit scene activity
			txtName.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					if (Config.isVibrate)
						new VibrateThread(getActivity().getApplicationContext())
								.start();
					FragmentManager fragmentManager = getActivity()
							.getSupportFragmentManager();
					FragmentTransaction transaction = fragmentManager
							.beginTransaction();
					/*EditSceneFragment editSceneFragment = (EditSceneFragment) fragmentManager
							.findFragmentByTag(EditSceneFragment.EDITSCENEFRAGMENT);
					if (editSceneFragment == null) {
						editSceneFragment = EditSceneFragment.newInstance(
								room_id, floor_id, sceneID, sceneName, mode,
								hour, minute);
					} else {
						editSceneFragment.refresh(room_id, floor_id, sceneID,
								sceneName, mode, hour, minute);
					}*/
					EditSceneFragment editSceneFragment = EditSceneFragment.newInstance(
							room_id, floor_id, sceneID, sceneName, mode,
							hour, minute);
					transaction.replace(R.id.activity_main_content,
							editSceneFragment,
							EditSceneFragment.EDITSCENEFRAGMENT);
					transaction.addToBackStack(null);
					transaction.setCustomAnimations(
							R.animator.fragment_slide_left_enter,
							R.animator.fragment_slide_left_exit,
							R.animator.fragment_slide_right_enter,
							R.animator.fragment_slide_right_exit);

					// Commit the transaction
					transaction.commit();

				}

			});

		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup viewgroup) {
			return View.inflate(context, R.layout.item_listview_scene_edit,
					null);
		}

		@Override
		public boolean isEnabled(int position) {
			// TODO Auto-generated method stub
			return false;
		}

		public class DelSceneReceiver extends BroadcastReceiver {

			private ProgressDialog mDialog;

			public DelSceneReceiver(ProgressDialog dialog) {
				mDialog = dialog;
			}

			@Override
			public void onReceive(Context context, Intent intent) {
				mDialog.cancel();
				context.unregisterReceiver(mDelSceneReceiver);
				if (intent
						.getAction()
						.equals(context
								.getString(R.string.txt_vn_lumi_smarthome_del_scenes_successful))) {

				} else if (intent
						.getAction()
						.equals(context
								.getString(R.string.txt_vn_lumi_smarthome_del_scenes_failed))) {
					showCustomDialog(R.string.txt_error,
							R.string.txt_error_cannot_connect_HC);
				}
			}

		}

		public void showCustomDialog(int title, int message) {
			AlertDialog.Builder ErrorDialog = new AlertDialog.Builder(
					new ContextThemeWrapper(context, R.style.AlertDialogCustom));

			ChangeFont changeFont = new ChangeFont(context);
			TextView tvTitle = new TextView(context);
			tvTitle = changeFont.changeFontTextView(tvTitle, title,
					LumiHome.fontBold, LumiHome.sizeTittle, Gravity.CENTER,
					context.getResources().getColor(R.color.green));
			ErrorDialog.setCustomTitle(tvTitle);
			ErrorDialog.setMessage(message);
			ErrorDialog.setNegativeButton(R.string.glb_txt_return,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.cancel();
						}
					});
			AlertDialog alertErrorDialog = ErrorDialog.create();
			alertErrorDialog.show();
			alertErrorDialog.getWindow().getAttributes();
			TextView tvMessage = (TextView) alertErrorDialog
					.findViewById(android.R.id.message);
			tvMessage = changeFont.changeFontTextView(tvMessage, message,
					LumiHome.font, LumiHome.sizeContent, Gravity.NO_GRAVITY,
					context.getResources().getColor(R.color.greenLight));

			Button btn1 = alertErrorDialog
					.getButton(DialogInterface.BUTTON_NEGATIVE);
			btn1.setTypeface(Typeface.createFromAsset(context.getAssets(),
					LumiHome.fontBold));
			btn1.setTextColor(context.getResources().getColor(
					R.color.greenActionbar));
			btn1.setTextSize(LumiHome.sizeButton);
		}

	}

	public static String convertIntArrayToString(int[] data) {
		String result = "";
		for (int i = 0; i < data.length; i++) {
			result += String.valueOf(data[i]) + ",";
		}
		return result;

	}

	public static int[] convertStringToIntArray(String str) {
		if (str == "")
			return null;
		String[] array = str.split(",");
		int[] result = new int[array.length];
		for (int i = 0; i < array.length; i++) {
			result[i] = Integer.parseInt(array[i]);
		}
		return result;
	}

	public static int[] convertArrayListToArray(ArrayList<Integer> input) {
		int[] result = new int[input.size()];
		for (int i = 0; i < input.size(); i++) {
			result[i] = input.get(i);
		}
		return result;
	}

}
